<?php

declare(strict_types=1);

namespace App\CustHub\Helpers;

use App\Common\Constants\GenderConstants;
use App\CustHub\Constants\MsgTypeConstants;
use function Hyperf\Collection\collect;

class TagReplacer
{
    /**
     * 批量替换标签
     *
     * @param string $template 模板字符串
     * @param array $replacements 替换的标签值数组（英文键）
     * @return string 替换后的字符串
     */
    public static function replaceTags(string $template, array $replacements): string
    {
        // 中文标签与英文键的映射关系
        $tagMapping = [
            '当前群名' => 'room_name',
            '编号' => 'number',
            '当前备注' => 'remark',
            '昵称' => 'nickname',
            '微信昵称' => 'nickname',
            '性别' => 'gender',
            '称呼/昵称' => 'call_name_nickname',
            '违规群成员昵称' => 'violating_member_nickname',
            '白名单成员昵称' => 'white_list_nickname',
            '添加日期' => 'add_time',
            '添加时间' => 'add_time',
            '违规原因' => 'violation_reason',
            '随机表情' => 'random_emoji',
            '手机号' => 'mobile'
            // 这里可以继续增加其他标签映射
        ];

        // 正则匹配所有标签，标签形式为 {标签名称}
        return preg_replace_callback('/\{(\S+?)\}/', function ($matches) use ($replacements, $tagMapping) {
            $chineseTag = $matches[1];
            // 如果中文标签存在映射关系，则查找替换值
            if (isset($tagMapping[$chineseTag]) && isset($replacements[$tagMapping[$chineseTag]])) {

                $value = $replacements[$tagMapping[$chineseTag]];

                if($chineseTag == '性别'){
                    $value = GenderConstants::getMessage($value);
                }

                if($chineseTag == '随机表情'){
                    $value = getRandomEmoji();
                }

                return $value;
            }

            // 如果没有找到对应的标签值，保持原样
            return $matches[0];
        }, $template);
    }

    public static function changeData(array $sendMessageData,array $data)
    {
        foreach ($sendMessageData as $k=>$item){
            if(!is_string($item['content'])) continue;
            $content = $item['content'];
            if(str_contains($content,'{@所有人}')){
                // 使用正则表达式仅对 {@所有人} 标签进行分割，同时保留标签
//                $pattern = '/(\{@所有人\})/';  // 匹配 {@所有人} 标签
//
//                // 使用 preg_split 来分割字符串，并确保保留 {@所有人} 标签
//                $splitArray = preg_split($pattern, $content, -1, PREG_SPLIT_DELIM_CAPTURE);
//                $newContent = [];
//                $separator = '';
//                foreach ($splitArray as $splitItem){
//                    if($splitItem === '{@所有人}'){
//                        $newContent[] = [
//                            'subtype' => 1,
//                            'text' => ''
//                        ];
//                        $separator = ' ';
//                    }else{
//                        $newContent[] = [
//                            'subtype' => 0,
//                            'text' => $separator.self::replaceTags($splitItem,$data)
//                        ];
//                    }
//                }
                $convertResult = self::convertLabelContent('所有人',$content,$data);
                $sendMessageData[$k]['msg_type'] = $convertResult['msg_type'];
                $sendMessageData[$k]['content'] = $convertResult['content'];
            }elseif (str_contains($content,'{@昵称}')){
                $convertResult = self::convertLabelContent('昵称',$content,$data);
                $sendMessageData[$k]['msg_type'] = $convertResult['msg_type'];
                $sendMessageData[$k]['content'] = $convertResult['content'];
            }else{
                $content = self::replaceTags($content,$data);
                $sendMessageData[$k]['content'] = $content;
            }
        }
        return $sendMessageData;
    }

    private static function convertLabelContent(string $label,string $content,array $data)
    {
        $pattern = "/(\{@{$label}\})/";  // 匹配 {@所有人} 标签

        // 使用 preg_split 来分割字符串，并确保保留 {@所有人} 标签
        $splitArray = preg_split($pattern, $content, -1, PREG_SPLIT_DELIM_CAPTURE);
        $newContent = [];
        $separator = '';
        $receiver=!empty($data['receiver'])?$data['receiver']:'';
        foreach ($splitArray as $splitItem){
            if($splitItem === "{@{$label}}"){
                if($label == '所有人'){
                    $newContent[] = [
                        'subtype' => 1,
                        'text' =>''
                    ];
                }else{
                    if(is_array($receiver)){
                        foreach ($receiver as $item){
                            $newContent[] = [
                                'subtype' => 1,
                                'text' => $item
                            ];
                        }
                    }else{
                        $newContent[] = [
                            'subtype' => 1,
                            'text' => $receiver
                        ];
                    }
                }
                $separator = ' ';
            }else{
                if(!empty($splitItem)){
                    $newContent[] = [
                        'subtype' => 0,
                        'text' => $separator.self::replaceTags($splitItem,$data)
                    ];
                }
            }
        }

        return [
            'msg_type' => MsgTypeConstants::MIXED_TEXT,
            'content' => $newContent
        ];
    }
}